package com.project.slsx.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.project.slsx.Constant.Constans;
import com.project.slsx.R;
import com.project.slsx.bean.OpenCardBean;
import com.project.slsx.bean.VIPBean;
import com.project.slsx.bean.VipBukaBean;
import com.project.slsx.bean.VipGuaShiBean;
import com.project.slsx.utils.DialogUtils;
import com.project.slsx.utils.DisplayUtils;
import com.project.slsx.utils.ParamsUtils;
import com.project.slsx.utils.UserManager;
import com.project.slsx.widget.dialog.BaseNiceDialog;
import com.project.slsx.widget.dialog.ViewConvertListener;
import com.project.slsx.widget.dialog.ViewHolder;

public class VIPActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = VIPActivity.class.getSimpleName();
    private LinearLayout rootVip;
    private TextView nickname;
    private TextView num;
    private TextView name;
    private TextView mobile;
    private TextView money;
    private TextView addtime;

    private VIPBean vipBean;
    private EditText edVipGuashi;
    private Button btnBubanOk;

    private Button btnSearch;
    private EditText edSearch;
    private String searchStr;
    //挂失
    private String password = "";
    //补办
    private String cardId;
    private String vipNumber;
    private String oldPassword;
    //充值
    private String amount;
    private String remark;
    //1 现金 2扫码支付
    private String type;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 1001:
                    VIPBean vipBean = (VIPBean) msg.obj;
                    VIPBean.ResultBean result = vipBean.getResult();
                    nickname.setText(result.getNickname());
                    num.setText(result.getVip_number());
                    name.setText(result.getName());
                    mobile.setText(result.getMobile());
                    money.setText(result.getMoney());
                    addtime.setText(result.getAddtime());
                    break;

                default:

                    break;
            }
        }
    };
    private OpenCardBean.ResultBean opencardBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_vip;
    }

    @Override
    public void initView() {
        findViewById(R.id.rl_back).setOnClickListener(this);
        TextView title = findViewById(R.id.tv_title);
        title.setText("会员");
        findViewById(R.id.tv_right).setVisibility(View.INVISIBLE);
        edSearch = findViewById(R.id.ed_vip_search);
        btnSearch = findViewById(R.id.btn_vip_search);
        btnSearch.setOnClickListener(this);
        edSearch.addTextChangedListener(new MySearchWahtcher());
        findViewById(R.id.btn_vip_open).setOnClickListener(this);

        rootVip = findViewById(R.id.ll_vip_detail);
        nickname = findViewById(R.id.tv_nickname);
        num = findViewById(R.id.tv_vip_num);
        name = findViewById(R.id.tv_vip_name);
        mobile = findViewById(R.id.tv_vip_mobile);
        money = findViewById(R.id.tv_vip_money);
        addtime = findViewById(R.id.tv_vip_addtime);

        findViewById(R.id.btn_vip_guashi).setOnClickListener(this);
        findViewById(R.id.btn_vip_buban).setOnClickListener(this);
        findViewById(R.id.btn_vip_chongzhi).setOnClickListener(this);

    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.btn_vip_search:
                if (TextUtils.isEmpty(searchStr)) {
                    showToast(mContext, "输入要查询的手机号或会员号");
                } else {
                    doSearch();
                }
                break;

            case R.id.btn_vip_open:
                Intent intent = new Intent(mContext, OpenCardActivity.class);
                startActivityForResult(intent, 1001);
                break;
            case R.id.btn_vip_guashi:
                DialogUtils.showDialog(R.layout.dialog_vip_guashi,
                        DisplayUtils.dp2px(mContext, 200),
                        DisplayUtils.dp2px(mContext, 190),
                        true,
                        guashiListener,
                        getSupportFragmentManager());
                break;
            case R.id.btn_vip_buban:
                DialogUtils.showDialog(R.layout.dialog_vip_buban,
                        DisplayUtils.dp2px(mContext, 200),
                        DisplayUtils.dp2px(mContext, 210),
                        true,
                        bubanListener,
                        getSupportFragmentManager());
                break;
            case R.id.btn_vip_chongzhi:
                DialogUtils.showDialog(R.layout.dialog_vip_chongzhi,
                        DisplayUtils.dp2px(mContext, 200),
                        DisplayUtils.dp2px(mContext, 210),
                        true,
                        chognzhiListener,
                        getSupportFragmentManager());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    private ViewConvertListener guashiListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            edVipGuashi = convertView.findViewById(R.id.ed_vip_guashi);
            edVipGuashi.addTextChangedListener(new GuashiWatcher());
            convertView.findViewById(R.id.btn_vip_guashi_cancel).setOnClickListener(v -> DialogUtils.dissmissDialog());
            convertView.findViewById(R.id.btn_vip_guashi_ok).setOnClickListener(v -> {
                if (TextUtils.isEmpty(password)) {
                    showToast(mContext, "请输入密码");
                } else {
                    doGuashi();
                }
            });
        }
    };

    private ViewConvertListener bubanListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            EditText edVipNewId = convertView.findViewById(R.id.ed_vip_buban_newid);
            EditText edVipCardId = convertView.findViewById(R.id.ed_vip_buban_newcardid);
            EditText edVipPsd = convertView.findViewById(R.id.ed_vip_buban_newpsd);
            edVipNewId.addTextChangedListener(new MyNewIdWatcher());
            edVipCardId.addTextChangedListener(new MyCardIdWatcher());
            edVipPsd.addTextChangedListener(new MyPasswordWatcher());
            convertView.findViewById(R.id.btn_vip_buban_ok).setOnClickListener(v -> {
                if (TextUtils.isEmpty(cardId)) {
                    showToast(mContext, "请输入会员号");
                    return;
                }
                if (TextUtils.isEmpty(vipNumber)) {
                    showToast(mContext, "请输入卡号");
                    return;
                }
                if (TextUtils.isEmpty(oldPassword)) {
                    showToast(mContext, "请输入密码");
                    return;
                }

                doBuBan();

            });

        }
    };

    private ViewConvertListener chognzhiListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            TextView currentMoney = convertView.findViewById(R.id.tv_vip_current_money);
            currentMoney.setText("当前余额:" + vipBean.getResult().getMoney() + "元");
            Button saoma = convertView.findViewById(R.id.btn_vip_saoma);
            Button cash = convertView.findViewById(R.id.btn_vip_cash);
            EditText edChongzhiMoney = convertView.findViewById(R.id.ed_vip_chongzhi_money);
            EditText edChongzhiPls = convertView.findViewById(R.id.ed_vip_chongzhi_pls);
            edChongzhiMoney.addTextChangedListener(new MyVipChongzhiWatcher());
            edChongzhiPls.addTextChangedListener(new MyVipPlsWatcher());
            saoma.setOnClickListener(v -> {
                if (TextUtils.isEmpty(amount)) {
                    showToast(mContext, "请输入金额");
                    return;
                }
                if (TextUtils.isEmpty(remark)) {
                    showToast(mContext, "请输入备注");
                }

                //充值
                doChongzhi();
            });
            cash.setOnClickListener(v -> {
                type = "1";
                if (TextUtils.isEmpty(amount)) {
                    showToast(mContext, "请输入金额");
                    return;
                }
                if (TextUtils.isEmpty(remark)) {
                    showToast(mContext, "请输入备注");
                }
                //充值
                doChongzhi();
            });
        }
    };

    private class MySearchWahtcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            searchStr = s.toString().trim();
        }
    }


    /**
     * 查询
     */
    private void doSearch() {
        HttpParams hp = new HttpParams();
        hp.put("op", "vipsearch");
        hp.put("token", UserManager.getUser().getToken());
        hp.put("uniacid", UserManager.getUser().getUniacid());
        hp.put("sid", UserManager.getUser().getSid());
        hp.put("keyword", searchStr);
        OkGo.<String>post(Constans.BASEURL)
                .tag("vip")
                .params(hp)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.i(TAG, "onSuccess: " + response.body());
                        vipBean = JSONObject.parseObject(response.body(), VIPBean.class);
                        if (vipBean.getErrno() == Constans.SUCCESS) {
                            rootVip.setVisibility(View.VISIBLE);
                            Message message = new Message();
                            message.what = 1001;
                            message.obj = vipBean;
                            mHandler.sendMessage(message);
                        } else {
                            showToast(mContext, vipBean.getErrmsg());
                            rootVip.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.i(TAG, "onError: ");
                        showToast(mContext, "error!");
                        rootVip.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                });
    }

    /**
     * 挂失
     */
    private void doGuashi() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("op", "vipstatus");
        httpParams.put("token", UserManager.getUser().getToken());
        httpParams.put("uniacid", UserManager.getUser().getUniacid());
        httpParams.put("sid", UserManager.getUser().getSid());
        httpParams.put("id", vipBean.getResult().getId());
        httpParams.put("password", password);
        OkGo.<String>post(Constans.BASEURL)
                .tag("guashi")
                .params(httpParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.i(TAG, "onSuccess: " + response.body());
                        VipGuaShiBean guashi = JSONObject.parseObject(response.body(), VipGuaShiBean.class);
                        if (guashi.getErrno() == Constans.SUCCESS) {
                            DialogUtils.dissmissDialog();
                        }
                        showToast(mContext, guashi.getErrmsg());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.i(TAG, "onError: " + response.toString());
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                });
    }

    private class GuashiWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            password = s.toString().trim();
        }
    }

    /**
     * 补办
     */
    private void doBuBan() {
        HttpParams hp = ParamsUtils.getVipreplaceParams();
        hp.put("id", vipBean.getResult().getId());
        hp.put("card_id", cardId);
        hp.put("vip_number", vipNumber);
        hp.put("password", oldPassword);
        OkGo.<String>post(Constans.BASEURL).tag("buban").params(hp).execute(new StringCallback() {

            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                DialogUtils.showLoading(loadListener, getSupportFragmentManager());
            }

            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
                VipBukaBean vipBukaBean = JSONObject.parseObject(response.body(), VipBukaBean.class);
                if (vipBukaBean.getErrno() == Constans.SUCCESS) {

                } else {

                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Log.i(TAG, "onFinish: ");
                DialogUtils.dissmissDialog();
            }
        });
    }

    //新id
    private class MyNewIdWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            cardId = s.toString().trim();
        }
    }

    //卡号
    private class MyCardIdWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            vipNumber = s.toString().trim();
        }
    }

    //密码
    private class MyPasswordWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            oldPassword = s.toString().trim();
        }
    }

    /**
     * 充值
     */

    private void doChongzhi() {
        HttpParams viprechargeParams = ParamsUtils.getViprechargeParams();
        viprechargeParams.put("id", vipBean.getResult().getId());
        viprechargeParams.put("amount", amount);
        viprechargeParams.put("remark", "");
        viprechargeParams.put("type", type);
        viprechargeParams.put("code", "");
        OkGo.<String>post(Constans.BASEURL).tag("chongzhi").params(viprechargeParams).execute(new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                DialogUtils.showLoading(getSupportFragmentManager());
            }

            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);

            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUtils.dissmissDialog();
            }
        });
    }

    //充值
    private class MyVipChongzhiWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            amount = s.toString().trim();
        }
    }

    //备注
    private class MyVipPlsWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            remark = s.toString().trim();
        }
    }


    //加载dialog
    private ViewConvertListener loadListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    OpenCardBean result = (OpenCardBean) data.getSerializableExtra("opencardresult");
                    opencardBean = result.getResult();
                    rootVip.setVisibility(View.VISIBLE);
                    nickname.setText(opencardBean.getNickname());
                    num.setText(opencardBean.getVip_number());
                    name.setText(opencardBean.getName());
                    mobile.setText(opencardBean.getMobile());
                    money.setText(opencardBean.getMoney());
                    addtime.setText(opencardBean.getAddtime());
                    Log.i(TAG, "onActivityResult: " + result.getResult());
                }
            }else {
                rootVip.setVisibility(View.GONE);
            }
        }
    }
}
